<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 2011 dec xiaohefeng@foxmail.com
 * */

class Cms extends CI_Controller {

	//
	var $gen_pnum;
	var $gen_cnum;
	var $gen_start;
	var $gen_end;
	
	function Cms(){
		parent::__construct();
		
		session_start();		
		//$this->load->library('session');		
		//$this->load->library('encrypt');
		
		$this->load->model('cms_model');
		
		//$qf_userid = $_SESSION['qf_userid'];
		$qf_userid = $_SESSION['qf_userid'];
		
		//if(!isset($_SESSION['qf_userid'])){
		if(!isset($qf_userid)){
			redirect('/login');
			return;
		}
	}
	
	public function index(){
		$data['tip'] = '';
		$this->load->view('main_view',$data);
	}
	
	public function drawVC()
	{		
		$this->load->library('captchaimage');		
        
        ob_start();
        
        //write session
            
        //$this->session->userdata('vcode') =  $vc;
        //$newdata = array('vcode'  => $vc);
		//$this->session->set_userdata($newdata);
		
		$vc = $this->captchaimage->getString();    
        $_SESSION['vcode'] = $vc;
        
        $this->captchaimage->setFont('./fonts/1.ttf',20);     
        $this->captchaimage->draw();  
              
        ob_flush();
        
	}
	
	public function logout(){
		session_unregister("qf_userid");
		session_unregister("qf_siteid");		
		//$this->session->unset_userdata('qf_userid');		
		redirect('/login');
	}
	
	public function nav(){
		$qf_userid = $_SESSION['qf_userid'];
		$data['userid'] = $qf_userid; //$_SESSION['qf_userid'];
		$this->load->view('nav_view',$data);		
	}
	
	public function doLoadColumn(){		
		//check session
		$qf_userid = $_SESSION['qf_userid'];
		if(!isset($qf_userid)){
			return ;
		}
		//
		$id = $this->uri->segment(3);
		
		$json = $this->cms_model->GetJsonData($id);
		if(!empty($json))
			echo ($json);
	}
	
	public function doLoadColumn_OldSys(){		
		//check session
		$qf_userid = $_SESSION['qf_userid'];
		if(!isset($qf_userid)){
			return ;
		}
		//
		$id = $this->uri->segment(3);
		
		$json = $this->cms_model->GetJsonData_OldSys($id);
		if(!empty($json))
			echo ($json);
	}
	
	public function blank(){
		$data['userid'] = $_SESSION['qf_userid'];
		$this->load->view('blank_view',$data);
	}	
	
	public function sites(){		
		//check auth
		$userid = $_SESSION['qf_userid'];
		if($userid != 'admin'){
			$this->load->view('blank_view');
			return ;
		}
		
		//delete
		$delact = $this->uri->segment(3);
		$delid = $this->uri->segment(4);		
		if( strcasecmp($delact, 'del') == 0 )
		{			
			if(!empty($delid)){		
				$data = array(
					'disabled' => 1
		        );				
				$this->db->where('sid', $delid);
				$this->db->update('qf_site', $data); 				
			}
		}
		
		//list
		$this->db->where('disabled','0'); 
		$this->db->order_by('sortno,sname'); 
		$data['query'] = $this->db->get('qf_site');
		$this->load->view('sites_view',$data);
	}
	
	public function sitesort(){
		$this->db->where('disabled','0'); 
		$this->db->order_by('sortno,sname'); 
		$data['query'] = $this->db->get('qf_site');
		$data['tip'] = '';
		
		$this->load->view('sitesort_view',$data);
	}
	
	public function savesitesort(){
		$this->db->where('disabled','0'); 
		$this->db->order_by('sortno,sname'); 
		$query = $this->db->get('qf_site');
		foreach ($query->result() as $row) {
			$txtid = 'txt_'.$row->sid;
			$data = array(
				'sortno' => $_POST[$txtid]
		    );	
			//$sql = "update qf_site set sortno='$_POST[$txtid]' where sid='$row->sid'";
			$this->db->where('sid',$row->sid);
			$this->db->update('qf_site',$data);
		}		
		redirect('/cms/sites');
	}
	
	public function addsite(){		
		$sid = $this->uri->segment(3);
		$data['sid']=$sid;
		$data['descr']='';
		$data['sname']='';
		$data['surl'] = '';
		$data['sitestatus'] = 0;
		$data['htmlpath'] = '';
		
		$data['templateid'] = '';
		$data['templatename'] = '';	
		
		if(!empty($sid))
		{	
			$this->db->where('sid',$sid);
			$query = $this->db->get('qf_site');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){
					$data['descr'] = $row['description'];
					$data['sname'] = $row['sname'];
					$data['surl'] = $row['surl'];
					$data['sitestatus'] = $row['sitestatus'];
					$data['htmlpath'] = $row['htmlpath'];
					$data['templateid'] = $row['templateid'];
				}
			}
			
			if(!empty($data['templateid'])){
				$this->db->where('tid',$data['templateid']);
				$query = $this->db->get('qf_template');
				if($query->num_rows() > 0){
					$row = $query->row();
					$data['templatename'] = $row->tname;
				}
			}
		}
		$this->load->view('addsite_view',$data);
	}
	
	public function savesite(){
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			$sid = '';
			if(empty($_POST['sid'])){
				//$sid = "s_".md5(uniqid(rand()));
				
				//sortno
				$countn = $this->db->count_all_results('qf_site');
				$countn++;
				
				$sid = "s_".str_pad($countn, 3, '0', STR_PAD_LEFT);
				
				$data = array(
					'sid' => $sid,
					'sname' => $_POST['sname'],
					'description' => $_POST['descr'],
					'surl' => $_POST['surl'],
					'sitestatus' => $_POST['sitestatus'],
					'templateid' => $_POST['templateid'],
					'sortno' => $countn,
					'disabled' => 0
		        );
		        $this->db->insert('qf_site',$data);
			}
			else{
				$data = array(
					'sname' => $_POST['sname'],
					'description' => $_POST['descr'],
					'surl' => $_POST['surl'],
					'sitestatus' => $_POST['sitestatus'],
					'templateid' => $_POST['templateid']
		        );
				$this->db->where('sid', $_POST['sid']);
				$this->db->update('qf_site', $data);
				
				$sid = $_POST['sid'];
			}
			
			//check folder
			$mode = 0777;
			$folderPath = 'www/'.$sid;	
			if(!file_exists($folderPath)){
				mkdir($folderPath,$mode);
			}
			$upfilepath = $folderPath.'/upfiles';
			if(!file_exists($upfilepath)){
				mkdir($upfilepath,$mode);
			}
			
			redirect('/cms/sites');
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	public function columns(){
		//param
		$sid = $this->uri->segment(3);
		$pid = $this->uri->segment(4);
		if($pid == '0')
			$pid = '';
		$cid = $this->uri->segment(5);	
		$delid = $this->uri->segment(6);			
		
		$data['sid'] =$sid;
		$data['pid'] =$pid;
		$data['cid'] =$cid;
		$data['ppid'] = '';
		$data['curName']='';
		//delete
		if( strcasecmp($cid, 'del') == 0 ){			
			if(!empty($delid)){		
				//$this->db->where('cid', $delid);
				//$this->db->delete('qf_column'); 				
				$data = array(
					'disabled' => 1
		        );				
				$this->db->where('cid', $delid);
				$this->db->update('qf_column', $data); 
				
				redirect('/cms/columns/'.$sid.'/'.$pid);
			}
		}
		
		//ini data
		if(!empty($pid)){
			$this->db->where('cid',$pid);
			$query = $this->db->get('qf_column');
			if($query->num_rows() > 0){
				$row = $query->row(); 
				//$data['curName'] = $row->cname;
				$data['ppid'] = $row->parentid;
				
				$navstr = '';
				$navarray = $this->cms_model->getnavcols_name($pid,$row->sid,0);
				if(is_array($navarray)){
					foreach ($navarray as $key=>$value){
						if(!empty($navstr))
							$navstr.='>>';
						$navstr.= "<a href=\"".$key."\" />".$value."</a>";
					}
				}
				if(!empty($navstr))
					$data['curName'] = $navstr.'>>'.$row->cname;
				else 
					$data['curName'] = $row->cname;
			}
		}
		else if(!empty($sid)){
			$this->db->where('sid',$sid);
			$query = $this->db->get('qf_site');
			if($query->num_rows() > 0){
				$row = $query->row(); 
				$data['curName'] = $row->sname;
				$data['ppid'] = '';
			}
		}		
		//list
		/*$where = "parentid='$pid' and sid='$sid' and disabled='0'";
		$this->db->where($where);
		$this->db->order_by('sortno asc'); 
		$data['query'] = $this->db->get('qf_column');*/
		$sql = "select * from qf_column where parentid='$pid' and sid='$sid' and disabled='0' order by sortno asc,updatetime asc";
		$data['query'] = $this->db->query($sql);
		$this->load->view('columns_view',$data);
	}
	
	public function columnsort(){
		$sid = $this->uri->segment(3);
		$pid = $this->uri->segment(4);
		if($pid == '0')
			$pid = '';
			
//		$this->db->where('disabled','0'); 
//		$this->db->where('pid',$pid); 
//		$this->db->order_by('sortno'); 
//		$data['query'] = $this->db->get('qf_column');
		
		$sql = "select * from qf_column where parentid='$pid' and sid='$sid' and disabled=0 order by sortno";
		$data['query'] = $this->db->query($sql);
		$data['tip'] = '';
		
		$data['sid'] = $sid;		
		$data['pid'] = $pid;
		
		$this->load->view('columnsort_view',$data);
	}
	
	public function savecolumnsort(){
		$sid = $_POST['sid'];
		$pid = $_POST['pid'];
		
		$sql = "select * from qf_column where parentid='$pid' and sid='$sid' and disabled=0 order by sortno";
		$query = $this->db->query($sql);
		//$query = $this->db->get('qf_column');
		foreach ($query->result() as $row) {
			$txtid = 'txt_'.$row->cid;
			$data = array(
				'sortno' => $_POST[$txtid]
		    );	
			//$sql = "update qf_site set sortno='$_POST[$txtid]' where sid='$row->sid'";
			$this->db->where('cid',$row->cid);
			$this->db->update('qf_column',$data);
		}		
		redirect('/cms/columns/'.$sid.'/'.$pid);
	}
	
	public function addcol(){
		//param
		$sid = $this->uri->segment(3);
		$pid = $this->uri->segment(4);
		$cid = $this->uri->segment(5);	
		
		$data['sid'] =$sid;
		$data['pid'] =$pid;
		$data['cid'] =$cid;		
		$data['cname'] ='';
		$data['display'] ='';
		$data['tid'] ='';
		$data['ctype'] ='';
		$data['sortno'] ='';
		$data['tname'] = '';
		$data['tag'] = '';
		$data['descr'] = '';
		$data['thumb'] = '';
		
		if(!empty($cid)){			
			$this->db->where('cid',$cid);
			$query = $this->db->get('qf_column');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){
					$data['cname'] = $row['cname'];
					$data['pid'] = $row['parentid'];
					$data['tid'] = $row['templateid'];
					$data['display'] = $row['display'];
					$data['ctype'] = $row['ctype'];
					$data['sid']= $row['sid'];
					$data['sortno'] = $row['sortno'];
					$data['tag'] = $row['tag'];
					$data['descr'] = $row['description'];
					$data['thumb'] = $row['thumb'];
				}
			}
			
			if(!empty($data['tid'])){
				$this->db->where('tid',$data['tid']);
				$query = $this->db->get('qf_template');
				if($query->num_rows() > 0){
					$row = $query->row();
					$data['tname'] = $row->tname;
				}
			}
		}		
		$this->load->view('addcol_view',$data);
	}
	
	public function editcol(){
		//param
		$sid = $this->uri->segment(3);
		$pid = ''; //$this->uri->segment(4);
		$cid = $this->uri->segment(4);	
		
		$data['sid'] =$sid;
		$data['pid'] =$pid;
		$data['cid'] =$cid;		
		$data['cname'] ='';
		$data['display'] ='';
		$data['tid'] ='';
		$data['ctype'] ='';
		$data['sortno'] ='';
		$data['tname'] = '';
		$data['tag'] = '';
		$data['descr'] = '';
		$data['thumb'] = '';
		
		if(!empty($cid)){			
			$this->db->where('cid',$cid);
			$query = $this->db->get('qf_column');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){
					$data['cname'] = $row['cname'];
					$data['pid'] = $row['parentid'];
					$data['tid'] = $row['templateid'];
					$data['display'] = $row['display'];
					$data['ctype'] = $row['ctype'];
					$data['sid']= $row['sid'];
					$data['sortno'] = $row['sortno'];
					$data['tag'] = $row['tag'];
					$data['descr'] = $row['description'];
					$data['thumb'] = $row['thumb'];
				}
			}
			
			if(!empty($data['tid'])){
				$this->db->where('tid',$data['tid']);
				$query = $this->db->get('qf_template');
				if($query->num_rows() > 0){
					$row = $query->row();
					$data['tname'] = $row->tname;
				}
			}
		}		
		$this->load->view('addcol_view',$data);
	}
	
	public function savecol(){ 		
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			
			//$countn = $this->db->count_all_results('qf_column');
			//$countn++;
			
			$pid = $_POST['pid'];
			$countp = 0;
			
			$sql = "select count(*) as c from qf_column where parentid='$pid'";
			$query = $this->db->query($sql);
			if($query->num_rows() > 0){
				$row = $query->row();
				$countp = $row->c;
			}
			$countp++;
				
			if(empty($_POST['cid'])){
				//$cid = "c_".md5(uniqid(rand()));
				
				$cid = $pid.str_pad($countp, 3, '0', STR_PAD_LEFT);
				if(empty($pid))
					$cid = "c_".$cid;
				
				$data = array(
					'cid' => $cid,
					'cname' => $_POST['cname'],
					//'ctype' => $_POST['ctype'],
					'description' => $_POST['descr'],
					'parentid' => $_POST['pid'],
					'templateid' => $_POST['tid'],
					'sid' => $_POST['sid'],
					'sortno' => $countp, //$_POST['sortno'],
					'display' => $_POST['display'],
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => $_POST['tag'],
					'thumb' => $_POST['thumb']
		        );
		        $this->db->insert('qf_column',$data);
			}
			else{
				$data = array(
					'cname' => $_POST['cname'],
					//'ctype' => $_POST['ctype'],
					'parentid' => $_POST['pid'],
					'templateid' => $_POST['tid'],
					'sid' => $_POST['sid'],
					//'sortno' => $_POST['sortno'],
					'display' => $_POST['display'],
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => $_POST['tag'],
					'thumb' => $_POST['thumb']
		        );
				$this->db->where('cid', $_POST['cid']);
				$this->db->update('qf_column', $data);
			}			
			
			redirect('/cms/columns/'.$_POST['sid'].'/'.$_POST['pid']);			
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	public function articles(){		
		//param
		$cid = $this->uri->segment(3);
		$pagenum = $this->uri->segment(4);
		
		$userid = $_SESSION['qf_userid'];
		$rlevel = $this->cms_model->GetRoleLevel($userid);
		
		$data['userid'] = $userid;
		$data['rlevel'] = $rlevel;
		$data['cid'] = $cid;
		$data['sid'] = '';
		
		//ini data
		if(!empty($cid)){			
			$this->db->where('cid',$cid);
			$query = $this->db->get('qf_column');
			if($query->num_rows() > 0){
				$row = $query->row(); 
				//$data['cname'] = $row->cname;
				$data['sid'] = $row->sid;
				
				$navstr = '';
				$navarray = $this->cms_model->getnavcols_name($cid,$row->sid,1);
				if(is_array($navarray)){
					foreach ($navarray as $key=>$value){
						if(!empty($navstr))
							$navstr.='>>';
						$navstr.= "<a href=\"".$key."\" />".$value."</a>";
					}
				}
				if(!empty($navstr))
					$data['cname'] = $navstr.'>>'.$row->cname;
				else 
					$data['cname'] = $row->cname;
			}
		}
		
		/*$this->db->where('cid',$cid);
		$this->db->where('disabled',0);
		$this->db->order_by('sortno asc, updatetime desc'); 
		$data['query'] = $this->db->get('qf_article');*/
		
		if(empty($pagenum))
			$pagenum = 1;
		$pagesize = 15;		
		$start = $pagesize * ($pagenum-1);
		
		//$sql = "select * from qf_article where cid='$cid' and disabled='0' order by sortno asc, updatetime desc";
		$sql = "select * from qf_article where (cid='$cid' or aid in (select aid from qf_articlecol where cid='$cid')) and disabled='0' order by sortno asc, updatetime desc";
		$sql .=" limit ".$start.",".$pagesize;
		$data['query'] = $this->db->query($sql);
		
		//pager
		$pagecount = 0;		
		$rownum = 0;
		$sql = "select count(*) as c from qf_article where (cid='$cid' or aid in (select aid from qf_articlecol where cid='$cid')) and disabled='0' ";
		$querycount = $this->db->query($sql);
		if($querycount->num_rows() > 0){
			$row = $querycount->row();
			$rownum = $row->c;
		}
		$pagecount = ceil($rownum / $pagesize);			
		$pager = $this->cms_model->GetPagerHtml($pagenum,$pagecount);
		$data['pager'] = $pager;

		$this->load->view('articles_view',$data);
	}
	
	public function delart(){
		$cid = $this->uri->segment(3);
		$delid = $this->uri->segment(4);
		
		if(!empty($delid)){		
			$this->db->where('aid',$delid);
			$query = $this->db->get('qf_article');
			if($query->num_rows() > 0){
				$row = $query->row();				
				$createby = $row->createby;
				$astatus = $row->astatus;
			}
		}
		
		$userid = $_SESSION['qf_userid'];
		$rlevel = $this->cms_model->GetRoleLevel($userid);
		$editable = false;
		if($rlevel > 0)
			$editable = true;
		else if($astatus == 0 && $createby == $userid){
			$editable = true;
		}
		
		if(!$editable){
			return ;
		}
		
		//delete
		if(!empty($delid)){		
			$data = array(
				'disabled' => 1
	        );
			$this->db->where('aid', $delid);
			$this->db->update('qf_article', $data);
			
			if($cid == 'null')
				echo("ok");
			else
				redirect('/cms/articles/'.$cid);
		}
	}
	
	public function addart(){
		//param
		$cid = $this->uri->segment(3);	
		
		$title='';
		$display=0;
		$tid = '';
		$atype='';
		$acontent = '';
		$titlethumbs = '';
		$sortno = '999';
		$tag = '';
		$linkurl = '';
		$atturl = '';
		
		$userid = $_SESSION['qf_userid'];
		$author = $this->cms_model->GetUserName($userid);
		
		$rlevel = $this->cms_model->GetRoleLevel($userid);

		if(!empty($aid)){		
			$this->db->where('aid',$aid);
			$query = $this->db->get('qf_article');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){			    
			        $title = $row['title'];
					$cid = $row['cid'];
					$tid = $row['templateid'];
					$display = $row['display'];
					$atype = $row['atype'];
					$acontent= $row['acontent'];
					$titlethumbs= $row['titlethumbs'];
					$sortno = $row['sortno'];
					$author = $row['author'];
					$tag = $row['tag'];
					$linkurl = $row['linkurl'];
					$atturl = $row['atturl'];
			    }
			}
		}
		$data['aid'] = '';
		$data['cid'] = $cid;
		$data['title'] = $title;
		$data['display'] = $display;
		$data['tid'] = $tid;
		$data['tname'] = '';
		$data['atype'] = $atype;
		$data['acontent'] = $acontent;
		$data['titlethumbs'] = $titlethumbs;
		$data['sortno'] = $sortno;
		$data['author'] = $author;
		$data['tag'] = $tag;
		$data['linkurl'] = $linkurl;
		$data['atturl'] = $atturl;
		$data['rlevel'] = $rlevel;
		
		$data['editable'] = true;
		$data['popup'] = '';
		$data['keyword'] = '';
		$data['attlist'] = '';
		
		$this->load->view('addart_view',$data);
	}
	
	public function editart(){
		//param
		$cid = '';
		$aid = $this->uri->segment(3);	
		
		$title='';
		$display=0;
		$tid = '';
		$atype='';
		$acontent = '';
		$titlethumbs = '';
		$sortno = '999';
		$author = '';
		$tag = '';
		$linkurl = '';
		$atturl = '';
		
		$createby = '';
		$astatus = 0;
		$keyword = '';

		if(!empty($aid)){		
			$this->db->where('aid',$aid);
			$query = $this->db->get('qf_article');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){			    
			        $title = $row['title'];
					$cid = $row['cid'];
					$tid = $row['templateid'];
					$display = $row['display'];
					$atype = $row['atype'];
					$acontent= $row['acontent'];
					$titlethumbs= $row['titlethumbs'];
					$sortno = $row['sortno'];
					$author = $row['author'];
					$tag = $row['tag'];
					$linkurl = $row['linkurl'];
					$atturl = $row['atturl'];
					
					$createby = $row['createby'];
					$astatus = $row['astatus'];
					$keyword = $row['keyword'];
			    }
			}
		}
		$data['aid'] = $aid;
		$data['cid'] = $cid;
		$data['title'] = $title;
		$data['display'] = $display;
		$data['tid'] = $tid;
		
		$tname = '';
		$sql = "select tname from qf_template where tid='$tid'";
		$tquery = $this->db->query($sql);
		if($tquery->num_rows() > 0){
			$row = $tquery->row();
			$tname = $row->tname;
		}				
		$data['tname'] = $tname;
		
		$data['atype'] = $atype;
		$data['acontent'] = $acontent;
		$data['titlethumbs'] = $titlethumbs;
		$data['sortno'] = $sortno;
		$data['author'] = $author;
		$data['tag'] = $tag;
		$data['linkurl'] = $linkurl;
		$data['atturl'] = $atturl;
		
		$userid = $_SESSION['qf_userid'];
		$rlevel = $this->cms_model->GetRoleLevel($userid);
		$editable = false;
		if($rlevel > 0)
			$editable = true;
		else if($astatus == 0 && $createby == $userid){
			$editable = true;
		}
		$data['editable'] = $editable;
		
		$data['popup'] = '';
		$popup = $this->uri->segment(4);
		if(strcasecmp($popup, 'popup')==0)	
			$data['popup'] = 'yes';
			
		$data['keyword'] = '';
		
		//attlist		
		$attlist = '';
		$sql = "select * from qf_articleatt where aid='$aid'";
		$aquery = $this->db->query($sql);
		$n = 0;
		$temp = '';
		foreach ($aquery->result() as $row){
			$n++;
			//$("#div_attlist").append("<p><span>" + fname + "</span>&nbsp;<input type='hidden' id='attlist_name_" + num + "' name='attlist_name_" + num + "' value='" + fname + "' /><input type='hidden' id='attlist_id_" + num + "' name='attlist_id_" + num + "' value='*' /><a href=\"#\" onclick=\"javascript:delatt(this);\">删除</a></p>");
			$temp .= "<p><a href='/upfiles/files/".$row->attname."'>".$row->attname."</a>&nbsp;&nbsp;&nbsp;&nbsp;<input type='hidden' name='attlist_".$row->attid."_".$n."' value='$row->attname' /><a href=\"#\" onclick=\"javascript:delatt(this);\">删除</a></p>";
		}
		$data['attlist'] = $temp;
		
		$this->load->view('addart_view',$data);
	}
	
	public function saveart(){ 		
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			
			$display = 0;
			if(!empty($_POST['display']))
				$display = 1;
			
			$atype = $_POST['atype'];
			$acontent = '';
			$linkurl = '';
			$atturl = '';
			$tag = '';
			if($atype == 0)
				$acontent = $_POST['acontent'];
			else if($atype == 1){
				$atturl = $_POST['atturl'];
			}
			else if($atype == 2){
				$linkurl = $_POST['linkurl'];
			}
			
			$astatus = 0;			
			$rlevel = $this->cms_model->GetRoleLevel($userid);
			if($rlevel > 0)
				$astatus = 1;
				
			$columnid = $_POST['cid'];
			$sid = $this->cms_model->GetSiteIDByColumnID($columnid);
			$aid = '';
				
			if(empty($_POST['aid'])){
				$aid = "a_".md5(uniqid(rand()));  
				
				$data = array(
					'aid' => $aid,
					'title' => $_POST['title'],
					'atype' => $_POST['atype'],
					'acontent' => $acontent,
					'templateid' => $_POST['tid'],
					'cid' => $_POST['cid'],
					'sortno' => $_POST['sortno'],
					'author' => $_POST['author'],
					'display' => $display,
					'disabled' => 0,
					'astatus' => $astatus,
					'createtime' => $ntime,
					'createby' => $userid,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => $tag,
					'titlethumbs' => $_POST['titlethumbs'],
					'linkurl' => $linkurl,
					'atturl' => $atturl,
					'sid' => $sid
		        );
		        $this->db->insert('qf_article',$data);
			}
			else{	
				$data = array(
					'title' => $_POST['title'],
					'atype' => $_POST['atype'],
					'acontent' => $acontent,
					'templateid' => $_POST['tid'],
					'cid' => $_POST['cid'],
					'sortno' => $_POST['sortno'],
					'author' => $_POST['author'],
					'display' => $display,
					'disabled' => 0,
					'astatus' => $astatus,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => $tag,
					'titlethumbs' => $_POST['titlethumbs'],
					'linkurl' => $linkurl,
					'atturl' => $atturl
		        );
		        $aid = $_POST['aid'];
				$this->db->where('aid', $_POST['aid']);
				$this->db->update('qf_article', $data);
			}
			
			//attlist attlist_id_
			$sql = "delete from qf_articleatt where aid='$aid'";
			$this->db->query($sql);			
			foreach($_POST as $key=>$value){
				if(strlen($key)< 9) continue;
				if(substr($key,0,8) == 'attlist_'){
					$temparray = explode('_', $key);
					$attid = $temparray[1];					
					if($attid == "0")
						$attid = md5(uniqid(rand()));
					
					$data = array(
						'attid' => $attid,
						'aid' => $aid,
						'attname' => $value,
						'atturl' => '/upfiles/files/'.$value,						
						'updatetime' => $ntime
			        );
			        $this->db->insert('qf_articleatt',$data);
				}
			}
			
			$popup = $_POST['hidpopup'];
			if(empty($popup))
				redirect('/cms/articles/'.$_POST['cid']);
			else 
				echo("<script>window.close();</script>");		
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	//just copy
	/*public function copyart(){
		$aids = $_POST['aid'];
		$cids = $_POST['cid'];
		
		if(empty($aids) || empty($cids)){
			return;
		}
		
		$ntime = date("Y-m-d H:i:s" ,time());
		$userid = $_SESSION['qf_userid'];
		
		$aidary = explode(',', $aids);
		$cidary = explode(',', $cids);
		
		foreach ($aidary as $aid){
			if(empty($aid))
				continue;
			
			$sql = "select * from qf_article where aid='$aid'";
			$query = $this->db->query($sql);
			if($query->num_rows() > 0){
				$row = $query->row();
									
				foreach ($cidary as $cid){
					if(empty($cid))
						continue;
					
					$tempary = explode('|', $cid);
					$cid = $tempary[0];
				
					$newaid = "a_".md5(uniqid(rand()));  
					$array = array(
						'aid' => $newaid,
						'title' => $row->title,
						//'shorttitle'
						'atype' => $row->atype,
						'acontent' => $row->acontent,
						//'templateid' => $_POST['tid'],
						'asource' => 'copy',
						//'clicknum'
						//'aeditor'
						'cid' => $cid,
						'sortno' => $row->sortno,
						'author' => $row->author,
						'display' => $row->display,
						'disabled' => $row->disabled,
						'astatus' => $row->astatus,
						'createtime' => $row->createtime,
						'createby' => $row->createby,
						'updatetime' => $ntime,
						'updateby' => $userid,
						'tag' => $row->tag,
						'titlethumbs' => $row->titlethumbs,
						'linkurl' => $row->linkurl,
						'atturl' => $row->atturl,
						'sid' => $row->sid
					);
					$this->db->set($array);
					$this->db->insert('qf_article');
				}
			}
		}
		echo('ok');		
	}*/
	
	public function copyart(){
		$aids = $_POST['aid'];
		$cids = $_POST['cid'];
		
		if(empty($aids) || empty($cids)){ return; }
		
		$aidary = explode(',', $aids);
		$cidary = explode(',', $cids);
		
		foreach ($aidary as $aid){
			if(empty($aid)) continue;

			foreach ($cidary as $cid){
				if(empty($cid)) continue;
				
				$tempary = explode('|', $cid);
				$cid = $tempary[0];
					
				$sql = "select * from qf_articlecol where aid='$aid' and cid='$cid'";
				$query = $this->db->query($sql);
				if($query->num_rows() > 0)
					continue;
					
				$array = array(
					'aid' => $aid,
					'cid' => $cid
				);
				$this->db->set($array);
				$this->db->insert('qf_articlecol');
			}
		}
		echo('ok');		
	}
	
	public function searchart(){		
		$userid = $_SESSION['qf_userid'];
		$data['sites'] =$this->cms_model->ListUserSites($userid);
		$data['createby'] = $userid;
		
		$ntime = date("Y-m-d" ,time());
		$data['dtbegin'] = date("Y-m-d" ,strtotime("-7 day")); 
		$data['dtend'] = date("Y-m-d" ,strtotime("+1 day")); 
		
		$this->load->view('searchart_view',$data);
	}
	
	public function dosearchart(){
		//permission
		$userid = $_SESSION['qf_userid'];
		$rlevel = $this->cms_model->GetRoleLevel($userid);
		
		
		//query param
		$sid = $_POST['sid'];
		$cid = $_POST['cid'];
		$title = $_POST['title'];
		$dtbegin = $_POST['dtbegin'];
		$dtend = $_POST['dtend'];		
		$createby = $_POST['createby'];
		$astatus = $_POST['astatus'];		
		$atype = $_POST['atype'];
		$pagenum = $_POST['pagenum'];
		
		//query result
		$where = '';
		if(!empty($sid))
			$where.=" and sid='$sid'";
		if(!empty($cid))
			//$where.=" and cid='$cid'";
			$where.="(cid='$cid' or aid in (select aid from qf_articlecol where cid='$cid'))";
		if(!empty($title))
			$where.=" and title like '%$title%'";
		if(!empty($dtbegin))
			//$where.=" and updatetime>=UNIX_TIMESTAMP('".$dtbegin." 00:00:00')";
			$where.=" and updatetime>='".$dtbegin." 00:00:00'";
		if(!empty($dtend))
			//$where.=" and updatetime<=UNIX_TIMESTAMP('".$dtend." 00:00:00')";
			$where.=" and updatetime<='".$dtend." 00:00:00'";
		if(!empty($createby))
			$where.=" and createby='$createby'";
		if($astatus != '')
			$where.=" and astatus='$astatus'";
		if($atype != '')
			$where.=" and atype='$atype'";
		
		//pagesize
		if(empty($pagenum))
			$pagenum = 1;
		$pagesize = 15;		
		$start = $pagesize * ($pagenum-1);		
		
		$sql = "select * from qf_article where disabled=0 ".$where." order by sortno asc, updatetime desc";
		$sql .=" limit ".$start.",".$pagesize;
		$query = $this->db->query($sql);

		//datatable
		$output = '';
		$output.= "<table class='commonTable' width='100%' cellspacing='0' cellpadding='5' >";
	    $output.= "<tr>";
	    $output.= "<th><input id='ckall' name='ckall' type='checkbox' id='chk_All' onclick='chkall(this)'></th>";
		$output.= "<th>标题</th>";
		$output.= "<th>类型</th>";
		$output.= "<th>更新时间</th>";
		$output.= "<th>发布人</th>";
		$output.= "<th>是否显示</th>";
		$output.= "<th>权重</th>";
		$output.= "<th>状态</th>";
		$output.= "<th width='60' >";
		$output.= "</th>";
	    $output.= "</tr>";
		$n=0;
		foreach ($query->result_array() as $row){ 
			$n++;
			$output.= "<tr>";
			$output.= "<td><input type='checkbox' id='chk_".$n." name='chk' value='".$row['aid']."' /></td>";
			$output.= "<td><a href=\"javascript:editart('".$row['aid']."')\">".$row['title']."</a></td>";
			$output.= "<td>";
			switch ($row['atype']){
				case '0':
					$output.= "文档";
					break;
				case '1':
					$output.= "附件";
					break;
				case '2':
					$output.= "超链接";
					break;
			}
			$output.= "</td>";
			$output.= "<td>".$row['updatetime']."</td>";
			$output.= "<td>".$row['createby']."</td>";
			$output.= "<td>";
			if($row['display']==0)
				$output.= "<font color='#009933'>显示</font>";
			else 
				$output.= "<font color='#D14836'>隐藏</font>";
			$output.= "</td>";
			$output.= "<td>".$row['sortno']."</td>";
			$output.= "<td>";
			if($row['astatus']==0)
				$output.= "<font color='#D14836'>待审</font>";
			else
				$output.= "<font color='#009933'>已审</font>";
			$output.= "</td>";
			
			$editable = false;
			if($rlevel > 0)
				$editable = true;
			else if($row['astatus']==0 && $row['createby'] == $userid){
				$editable = true;
			}
			if($editable){	
				$output.= "<td><a href=\"javascript:editart('".$row['aid']."')\">编辑</a>&nbsp;<a href=\"javascript:delart('".$row['aid']."') \">删除</a></td>";
			}
			else{
				$output.= "<td><font color='#dcdcdc'>编辑&nbsp;删除</font></td>";
			}
			$output.= "</tr>";
		}
		$output.= "</table>";
		
		//pager
		$pagecount = 0;		
		$rownum = 0;
		$sql = "select count(*) as c from qf_article where disabled=0 ".$where;
		$querycount = $this->db->query($sql);
		if($querycount->num_rows() > 0){
			$row = $querycount->row();
			$rownum = $row->c;
		}
		$pagecount = ceil($rownum / $pagesize);			
		$pager = $this->cms_model->GetPagerHtml($pagenum,$pagecount);
		$output .= $pager;
		
		echo($output);	
	}
	
	public function templates(){	
		//check auth
		$userid = $_SESSION['qf_userid'];
		if($userid != 'admin'){
			$this->load->view('deny_view');
			return ;
		}
			
		//param
		$delact = $this->uri->segment(3);
		$delid = $this->uri->segment(4);
		
		//delete
		if( strcasecmp($delact, 'del') == 0 ){			
			if(!empty($delid)){		
				$data = array(
					'disabled' => 1
		        );
				$this->db->where('tid', $delid);
				$this->db->update('qf_template', $data);				
				//$this->db->where('aid', $delid);
				//$this->db->delete('qf_article'); 
				
				redirect('/cms/templates/','refresh');
				return ;
			}
		}
		
		//list
		$this->db->where('disabled',0);
		$this->db->order_by('tid asc'); 
		$data['query'] = $this->db->get('qf_template');

		$this->load->view('templates_view',$data);
	}
	
	public function addtpl(){		
		$data['tid'] = '';
		$data['tname'] = '';
		$data['ttype'] = '';
		$data['descr'] = '';
		$data['tcontent'] = '';
		$data['scontent'] = '';
		$data['thumbs'] = '';
		$data['tip'] = '';
		
		$this->load->view('addtpl_view',$data);
	}
	
	public function edittpl(){
		//param		
		$tid = $this->uri->segment(3);
		$tip = $this->uri->segment(4);
		if($tip=='y')
			$tip = '保存成功!';
		if($tip=='n')
			$tip = '保存失败!';
		
		$data['tid'] = '';
		$data['tname'] = '';
		$data['ttype'] = '';
		$data['descr'] = '';
		$data['tcontent'] = '';
		$data['scontent'] = '';
		$data['thumbs'] = '';
		$data['tip'] = $tip;

		if(!empty($tid)){		
			$this->db->where('tid',$tid);
			$query = $this->db->get('qf_template');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){			    
			        $data['tid'] = $row['tid'];
					$data['tname'] = $row['tname'];
					$data['ttype'] = $row['ttype'];
					$data['descr'] = $row['descr'];
					//$content = $this->cms_model->SpHtml2Text($row['tcontent']);
					$content = str_replace("textarea", "#textarea#", $row['tcontent']);
					$data['tcontent'] = $content;
					$data['scontent'] = $row['scontent'];
					$data['thumbs'] = $row['thumbs'];
			    }
			}
		}		
		$this->load->view('addtpl_view',$data);
	}
	
	public function savetpl(){ 		
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			
			if(empty($_POST['tid'])){
				$countn = $this->db->count_all_results('qf_template');
				$countn++;
				
				$tid = "t_".str_pad($countn, 3, '0', STR_PAD_LEFT);
				
				//$tid = "t_".md5(uniqid(rand()));  
				
				$data = array(
					'tid' => $tid,
					'tname' => $_POST['tname'],
					'ttype' => $_POST['ttype'],
					'descr' => $_POST['descr'],
					'tcontent' => str_replace("#textarea#", "textarea", $_POST['tcontent']) , //ereg_replace("#textarea", "textarea", $POST['tcontent']), //
					'scontent' => $_POST['scontent'], //ereg_replace(" ", "&nbsp;", $_POST['scontent']),
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'thumbs' => $_POST['thumbs'],
					'tag' => ''
		        );
		        $this->db->insert('qf_template',$data);
		        
		        //save tpl
		        $filepath = "application/views/templates/".$tid.".tpl";
		        if (is_file ($filepath)){  
				 @unlink ($filepath);
				}  
		        $content =  str_replace("#textarea#", "textarea", $_POST['tcontent']);//$_POST['tcontent'];
		        
        		$fp = fopen($filepath, "w");
				//fwrite($fp, iconv("GB2312","UTF-8",$content));
				fwrite($fp, $content);
				fclose($fp);
				
				redirect('/cms/templates/');
			}
			else{	
				$data = array(
					'tname' => $_POST['tname'],
					'ttype' => $_POST['ttype'],
					'descr' => $_POST['descr'],
					'tcontent' => str_replace("#textarea#", "textarea", $_POST['tcontent']), //$_POST['tcontent'], //ereg_replace(" ", "&nbsp;", $_POST['tcontent']),
					'scontent' => $_POST['scontent'], //ereg_replace(" ", "&nbsp;", $_POST['scontent']),
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'thumbs' => $_POST['thumbs'],
					'tag' => ''
		        );
				$this->db->where('tid', $_POST['tid']);
				$this->db->update('qf_template', $data);
				
				//save tpl
				$tid = $_POST['tid'];
		        $filepath = "application/views/templates/".$tid.".tpl";
		        $filepath_html = "application/views/templates/".$tid."_html.tpl";
		        
		        if (is_file ($filepath)){  
				 @unlink ($filepath);
				}  
		        $content =  str_replace("#textarea#", "textarea", $_POST['tcontent']);//$_POST['tcontent'];		        
        		$fp = fopen($filepath, "w");
        		//log_message('error',$content);
        		//fwrite($fp, iconv("UTF-8","UTF-8",$content));
				fwrite($fp, $content);
				fclose($fp);
				
				if (is_file ($filepath_html)){  
				 @unlink ($filepath_html);
				}  
		        $content = $_POST['scontent'];		        
        		$fph = fopen($filepath_html, "w");
				fwrite($fph, $content);
				fclose($fph);
				
				redirect('/cms/edittpl/'.$tid.'/y');
			}		
			
			//redirect('/cms/templates/');
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	public function roles(){
		//check auth
		$userid = $_SESSION['qf_userid'];
		if($userid != 'admin'){
			$this->load->view('deny_view');
			return ;
		}
				
		//param
		$delact = $this->uri->segment(3);
		$delid = $this->uri->segment(4);
		
		//delete
		if( strcasecmp($delact, 'del') == 0 ){			
			if(!empty($delid)){		
				/*$data = array(
					'disabled' => 1
		        );
				$this->db->where('tid', $delid);
				$this->db->update('qf_template', $data);*/				
				$this->db->where('roleid', $delid);
				$this->db->delete('qf_role'); 
				
				redirect('/cms/roles/','refresh');
				return ;
			}
		}
		
		//list
		/*$this->db->where('disabled',0);
		$this->db->order_by('rolename asc'); 		
		$data['query'] = $this->db->get('qf_role');*/
		
		$sql = "select r.*, s.sname from qf_role r left join qf_site s on r.sid=s.sid where r.disabled=0  order by r.rolename";
		$data['query'] = $this->db->query($sql);

		$this->load->view('roles_view',$data);
	}
	
	public function addrole(){		
		$data['roleid'] = '';
		$data['rolename'] = '';
		$data['descr'] = '';
		$data['sid'] = '';
		$data['sname'] = '';
		$data['rolelevel'] = '';
		
		$this->load->view('addrole_view',$data);
	}
	
	public function editrole(){
		//param		
		$rid = $this->uri->segment(3);
		
		$data['roleid'] = '';
		$data['rolename'] = '';
		$data['descr'] = '';
		$data['sid'] = '';
		$data['sname'] = '';
		$data['rolelevel'] = '';

		if(!empty($rid)){		
			$this->db->where('roleid',$rid);
			$query = $this->db->get('qf_role');
			if($query->num_rows() > 0){
				foreach ($query->result_array() as $row){			    
			        $data['roleid'] = $row['roleid'];
					$data['rolename'] = $row['rolename'];
					$data['descr'] = $row['descr'];
					$data['sid'] = $row['sid'];
					$data['rolelevel'] = $row['rolelevel'];					
			    }
			}
			if(!empty($data['sid'])){
				$this->db->where('sid',$data['sid']);
				$query = $this->db->get('qf_site');
				if($query->num_rows() > 0){
					$row = $query->row();
					$data['sname'] =$row ->sname;
				}
			}
		}		
		$this->load->view('addrole_view',$data);
	}
	
	public function saverole(){ 		
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			
			if(empty($_POST['roleid'])){
				$rid = "r_".md5(uniqid(rand()));  
				
				$data = array(
					'roleid' => $rid,
					'rolename' => $_POST['rolename'],
					'descr' => $_POST['descr'],
					'sid' => $_POST['sid'],
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => '',
					'rolelevel' => $_POST['rolelevel']
		        );
		        $this->db->insert('qf_role',$data);
			}
			else{	
				$data = array(
					'rolename' => $_POST['rolename'],
					'descr' => $_POST['descr'],
					'sid' => $_POST['sid'],
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => '',
					'rolelevel' => $_POST['rolelevel']
		        );
				$this->db->where('roleid', $_POST['roleid']);
				$this->db->update('qf_role', $data);
			}			
			
			redirect('/cms/roles/');			
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	public function choosesite(){
		
		//列出当前用户所属的站点
		$this->db->order_by('sortno asc'); 
		$data['query'] = $this->db->get('qf_site');
		$userid = $_SESSION['qf_userid'];
		$data['filter'] = $this->cms_model->ListSiteByUserID($userid);
		//if(strtolower($userid) == 'admin')
			$data['curuserid'] = strtolower($userid);
		$this->load->view('choosesite_view',$data);
	}
	
	public function users(){
		//check auth
		$userid = $_SESSION['qf_userid'];
		if($userid != 'admin'){
			$this->load->view('deny_view');
			return ;
		}
		
		//param
		$delact = $this->uri->segment(3);
		$delid = $this->uri->segment(4);
		
		//delete
		if( strcasecmp($delact, 'del') == 0 ){			
			if(!empty($delid) && strtolower($delid) != 'admin'){		
				$data = array(
					'disabled' => 1
		        );
				$this->db->where('uid', $delid);
				$this->db->update('qf_user', $data);			
				//$this->db->where('roleid', $delid);
				//$this->db->delete('qf_role'); 
				
				redirect('/cms/users/','refresh');
				return ;
			}
		}
		
		//list
		$this->db->where('disabled',0);
		$this->db->order_by('uid asc'); 
		$data['query'] = $this->db->get('qf_user');

		$this->load->view('users_view',$data);
	}
	
	public function adduser(){		
		$data['uid'] = '';
		$data['uname'] = '';
		$data['isedit'] = '';
		$data['tip'] = '';
		
		$this->load->view('adduser_view',$data);
	}
	
	public function edituser(){
		//param		
		$uid = $this->uri->segment(3);
		
		$data['uid'] = '';
		$data['uname'] = '';
		$data['isedit'] = '1';
		$data['tip'] = '';
		
		if(!empty($uid)){	
			$uid = strtolower($uid);	
			$this->db->where('uid',$uid);
			$query = $this->db->get('qf_user');
			if($query->num_rows() > 0){
				$row = $query->row() ;		    
			    $data['uid'] = $row->uid;
				$data['uname'] = $row->uname;				
			}
		}
		$this->load->view('edituser_view',$data);
	}
	
	public function saveuser(){ 		
		try{
			$ntime = date("Y-m-d H:i:s" ,time());
			$userid = $_SESSION['qf_userid'];
			$uid = strtolower($_POST['uid']);
			
			if(empty($_POST['isedit'])){
				//uid repeat check
				if($this->cms_model->ExistUserID($uid)){
					$data['uid'] = $uid;
					$data['uname'] = $_POST['uname'];
					$data['isedit'] = '';
					$data['tip'] = '用户名已经存在!';
					$this->load->view('adduser_view',$data);					
					return;
				}
				
				$pwdstr = '';
				if(!empty($_POST['pwd']))
					$pwdstr = $this->encrypt->encode($_POST['pwd']);
				$data = array(
					'uid' => $uid,
					'uname' => $_POST['uname'],
					'pwd' => $pwdstr,
					'disabled' => 0,
					'updatetime' => $ntime,
					'updateby' => $userid,
					'tag' => ''
		        );
		        $this->db->insert('qf_user',$data);
			}
			else{	
				$data = array(
					'uname' => $_POST['uname'],
					'updatetime' => $ntime,
					'updateby' => $userid
		        );
				$this->db->where('uid', $uid);
				$this->db->update('qf_user', $data);
			}			
			
			redirect('/cms/users/');			
		}
		catch (Exception $ex){
			log_message($ex->getMessage());
		}
	}
	
	public function userroles(){
		$uid = $this->uri->segment(3);
		
		$data['uname']='';
		$data['uid']=$uid;
		if(!empty($uid))
			$data['uname'] = $this->cms_model->GetUserName($uid);
		
		//list
		$sql = "select r.roleid, r.rolename, r.rolelevel from qf_userrole ur, qf_role r where ur.uid='$uid' and r.disabled=0 and ur.rid=r.roleid order  by r.rolename"; 
		$data['query'] = $this->db->query($sql);

		$this->load->view('userroles_view',$data);
	}
	
	public function adduserrole(){
		$uid = $this->uri->segment(3);
		
		$data['uid']=$uid;
		
		$sql = "select * from qf_role where disabled=0 "; 
		$data['query'] = $this->db->query($sql);
		
		$this->load->view('adduserrole_view',$data);
	}
	
	public function deluserrole(){
		$uid = $this->uri->segment(3);
		$rid = $this->uri->segment(4);
		
		$tag = $this->uri->segment(5);
		
		$this->db->where('uid',$uid);
		$this->db->where('rid',$rid);
		$this->db->delete('qf_userrole');
		
		if($tag == 'ur')
			redirect('/cms/userroles/'.$uid);
		else
			redirect('/cms/roleusers/'.$rid);
		//echo("<script>window.opener.location.reload();window.close();</script>");
	}
	
	public function saveuserrole(){
		$flag = $this->uri->segment(3);
		
		if($flag == 'ru'){
			$uidstr = $_POST['hiduid'];
			if(!empty($uidstr)){
				$uidary = explode(",", $uidstr);
				foreach ($uidary as $uid){
					if(empty($uid)) continue;
					
					if($this->cms_model->ExistUserRole($uid, $_POST['rid']))
						continue;
					
					$data = array(
						'uid' => $uid,
						'rid' => $_POST['rid']
			        );
			        $this->db->insert('qf_userrole',$data);
				}
			}
		}
		else{
			$ridstr = $_POST['hidrid'];
			if(!empty($ridstr)){
				$ridary = explode(",", $ridstr);
				foreach ($ridary as $rid){
					if(empty($rid)) continue;
					
					if($this->cms_model->ExistUserRole($_POST['uid'],$rid))
						continue;
					
					$data = array(
						'uid' => $_POST['uid'],
						'rid' => $rid
			        );
			        $this->db->insert('qf_userrole',$data);
				}
			}
		}		
		echo("<script>window.opener.location.reload();window.close();</script>");
	}
	
	public function roleusers(){
		$rid = $this->uri->segment(3);
		
		$data['rname']='';
		$data['rid']=$rid;
		if(!empty($rid))
			$data['rname'] = $this->cms_model->GetRoleName($rid);
		
		//list
		$sql = "select u.* from qf_userrole ur, qf_user u where ur.uid=u.uid and u.disabled=0 and ur.rid='$rid'
order by uname"; 
		$data['query'] = $this->db->query($sql);

		$this->load->view('roleusers_view',$data);
	}
	
	public function addroleuser(){
		$rid = $this->uri->segment(3);
		
		$data['rid'] = $rid;
		
		$sql = "select * from qf_user where disabled=0 "; 
		$data['query'] = $this->db->query($sql);
		
		$this->load->view('addroleuser_view',$data);
	}
	
	public function changepwd(){
		$uid = $_SESSION['qf_userid'];
		$data['uid'] = $uid;
		$data['uname'] = $this->cms_model->GetUserName($uid);
		$data['tip'] = '';
		
		$flag = $this->uri->segment(3);
		if($flag == '1')
			$data['tip'] = '保存成功!';
		else if($flag == '2')	
			$data['tip'] = '用户名与密码不匹配!';
			
		$this->load->view('changepwd_view',$data);
	}
	
	public function dochangepwd(){				
		$uid = $_SESSION['qf_userid'];
		$pwd = $_POST['pwd'];
		$newpwd = $_POST['newpwd'];
		
		$authcheck = false;
		$sql = "SELECT * FROM qf_user WHERE uid =".$this->db->escape($uid)." AND disabled = 0";
		$query = $this->db->query($sql); 
		if ($query->num_rows() >0){
			$row = $query->row();
			$pwdstr = $row->pwd;
			if(!empty($pwdstr)){			
				$pwdstr = $this->encrypt->decode($pwdstr);
				if(strcasecmp($pwdstr, $pwd) == 0) $authcheck = true;
			}
		}
		
		if($authcheck){
			if(!empty($newpwd))
				$newpwd = $this->encrypt->encode($newpwd);
			$data = array(
					'pwd' => $newpwd
		        );
			$this->db->where('uid', $uid);
			$this->db->update('qf_user', $data);
			
			redirect('/cms/changepwd/1');	
		}
		else{
			redirect('/cms/changepwd/2');			
		}		
		//$this->load->view('changepwd_view',$data);
	}
	
	public function choosetpl(){
		$flag = $this->uri->segment(3);	
			
		switch($flag){
			case 'home':
				$flag = 0;
				break;
			case 'column':
				$flag = 1;
				break;
			case 'article':
				$flag = 2;
				break;
		}
		
		$this->db->where('ttype',$flag);
		$this->db->where('disabled',0);
		$this->db->order_by('tname asc'); 
		$data['query'] = $this->db->get('qf_template');

		$this->load->view('choosetpl_view',$data);
	}
	
	public function choosecol(){
		$sid = $this->uri->segment(3);
		$multi = $this->uri->segment(4);
		$data['sid'] = $sid;
		$data['multi'] = $multi;		

		$this->load->view('choosecol_view',$data);
	}
	
	public function genhtml(){
		$userid = $_SESSION['qf_userid'];
		$level = $this->cms_model->GetRoleLevel($userid);
		if($level < 2){
			$this->load->view('deny_view');
			return ;
		}
		else{		
			$data['sites'] = $this->cms_model->ListUserSites($userid);			
			$this->load->view('genhtml_view',$data);
		}
	}
	
	public function dogenhtml(){
		$output = '';
		$this->gen_pnum = 0;
		$this->gen_cnum = 0;	
		$this->gen_start = date("Y-m-d H:i:s");
		$this->gen_end = '';	
		//$userid = $_SESSION['qf_userid'];
		
		//param
		$sid = $_POST['sid'];
		$cid = $_POST['cid'];
		
		if(empty($sid)){
			$output = '* no site';
			return ;
		}
		else{
			if(empty($cid)){
				//index page
				$this->genSiteIndexPage($sid);
				
				//top child column
				$sql = "select * from qf_column where parentid='' and sid='$sid' and disabled='0' order by sortno asc";
				$menucols = $this->db->query($sql);
				foreach ($menucols->result() as $row){
					$this->gencolhtml($sid,$row->cid);
				}
			}
			else{
				$this->gencolhtml($sid, $cid);
			}		
		}
		
		$output = "<table cellpadding='3'>";
		$output .= '<tr><td>处理完毕!</td><td></td></tr>';
		$output .= '<tr><td>开始时间:</td><td>'.$this->gen_start.'</td></tr>';
		$output .= '<tr><td>结束时间:</td><td>'.date("Y-m-d H:i:s").'</td></tr>';
		$output .= '<tr><td>栏目数量:</td><td>'.$this->gen_cnum.'</td></tr>';
		$output .= '<tr><td>页面数量:</td><td>'.$this->gen_pnum.'</td></tr>';
		$output .= '</table>';
		echo($output);			
	}
	
	public function genSiteIndexPage($sid){
		try{
			$mode = 0777;
			$folderPath = 'www/'.$sid;	
			if(!file_exists($folderPath)){
				mkdir($folderPath,$mode);
			}
			
			//find template
			$tarray = $this->cms_model->findtemplate($sid, 1);
			$tid = $tarray['tid'];
			$content = $tarray['content'];
			if(empty($content))
				return ;
			
			//menu columns
			$data['menucols'] = $this->cms_model->listmenucols($sid, 'menu', 1);
			
			//today
			$xingqi = $this->cms_model->getweekstr();
			$today = date('Y年m月d日').' '.$xingqi;
			$data['today'] = $today;
			
			/*----------------------*/		
			
			//view by smarty
			$tplfilename = $tid.'_html.tpl';
			$output = $this->smarty->view($tplfilename,$data,True);
			$filepath = $folderPath.'/index.html';
			$fp = fopen($filepath, "w");
			fwrite($fp, $output);
			fclose($fp);
			
			$this->gen_pnum++;
		}
		catch (Exception $ex){
			log_message('error',$ex->getMessage());			
		}
	}
	
	public function gencolhtml($sid, $cid){
		try{			
			//check folder
			$mode = 0777;
			$folderPath = 'www/'.$sid;		
			$pidstr = $this->cms_model->ListParentIDOfColumn($cid);
			if(!empty($pidstr))
				$folderPath.= '/'.$pidstr;						
			$folderPath.= '/'.$cid;
			if(!file_exists($folderPath)){
				mkdir($folderPath,$mode);
			}
			
			//find template
			$tarray = $this->cms_model->findtemplate($cid, 1);
			$tid = $tarray['tid'];
			$content = $tarray['content'];
				
			//create pages by pagenum
			$pagesize = 15;
			$pagecount = 0;		
			$rownum = 0;
			$sql = "select count(*) as c from qf_article where cid='$cid' and disabled='0' and display='0' and astatus='1' ";
			$querycount = $this->db->query($sql);
			if($querycount->num_rows() > 0){
				$row = $querycount->row();
				$rownum = $row->c;
			}
			$pagecount = ceil($rownum / $pagesize);	
			for ($i = 0; $i <= $pagecount; $i++) {
				if(!empty($content))
					$this->gencolpage($sid, $cid,  $tid, $folderPath, $i, $pagesize);
			}
			
			//create current column's articles page
			$sql = "select * from qf_article where cid='$cid' and disabled='0' and display='0' and astatus='1' order by updatetime desc limit 150 ";
			$queryart = $this->db->query($sql);
			foreach ($queryart->result() as $row){
				$this->genartpage($sid, $cid, $row->aid, $folderPath);
			}
			
			//digui child column
			$sql = "SELECT * FROM qf_column where disabled=0 and parentid='$cid' "; 
			$querychild = $this->db->query($sql); 
			foreach ($querychild->result() as $row){
				$this->gencolhtml($sid, $row->cid);
			}
			
			$this->gen_cnum++;
		}
		catch (Exception $ex){
			log_message('error',$ex->getMessage());			
		}
	}
	
	public function gencolpage($sid, $cid, $tid, $folderPath, $pagenum, $pagesize){
		try{
			/*---the data to view---*/
				
			//today
			$data['today'] = $this->cms_model->gettodayandweekstr();
			
			//
			$data['cid'] = $cid;
				
			//menu columns
			$data['menucols'] = $this->cms_model->listmenucols($sid, 'menu', 1);
							
			//nav column
			$navcolarray = $this->cms_model->getnavcols($cid, 1);
			$data['navcolarray'] = $navcolarray;
		
			//column name
			$data['colname'] = $this->cms_model->getcolname($cid);
			
			//sub columns
			$data['subcol'] = $this->cms_model->listsubcolumns($cid, 1);
			
			//articles
			if(empty($pagenum))
				$pagenum = 1;
			//$pagesize = 15;		
			$start = $pagesize * ($pagenum-1);
			
			/*$sql = "select * from qf_article where cid='$cid' and disabled='0' and display='0' and astatus='1' order by sortno asc, updatetime desc";
			$sql .=" limit ".$start.",".$pagesize;
			$queryarts = $this->db->query($sql);
			$data['articles'] = $queryarts->result_array();*/
			
			$data['articles'] = $this->cms_model->listcolarticles($cid, $pagenum, $pagesize, 1);
			
			//pager
			$pagecount = 0;		
			$rownum = 0;
			$sql = "select count(*) as c from qf_article where cid='$cid' and disabled='0' ";
			$querycount = $this->db->query($sql);
			if($querycount->num_rows() > 0){
				$row = $querycount->row();
				$rownum = $row->c;
			}
			$pagecount = ceil($rownum / $pagesize);			
			$pager = $this->cms_model->GetPagerHtml($pagenum,$pagecount);
			$data['pager'] = $pager;
			
			/*----------------------*/		
			
			//view by smarty
			$tplfilename = $tid.'_html.tpl';
			$output = $this->smarty->view($tplfilename,$data,True);
			//$output = iconv('GB2312','UTF-8',  $output);
			if($pagenum == 1){
				$filepath = $folderPath.'/index.html';
			}
			else 
				$filepath = $folderPath.'/index_'.$pagenum.'.html';
			//$filepath = $folderPath.'/index'.$pagenum.'.html';
			$fp = fopen($filepath, "w");
			fwrite($fp, $output);
			fclose($fp);
			
			$this->gen_pnum++;
		}
		catch (Exception $ex){
			log_message('error',$ex->getMessage());			
		}
	}
	
	public function genartpage($sid, $cid, $aid, $folderPath){
		/*---the data to view---*/
			
		//today
		$data['today'] = $this->cms_model->gettodayandweekstr();
				
		//
		$sid = '';
		$cid = '';
		$tid='';
		$tcontent = '';
		$atitle='';
		$acontent = '';
		$atype = '';
		$updatetime = '';
		
		$sql = "select * from qf_article where aid='$aid'";
		$query = $this->db->query($sql);
		if($query->num_rows() > 0){
			$row = $query->row();
			$sid = $row->sid;
			$tid = $row->templateid;
			$acontent = $row->acontent;
			$author = $row->author;
			$updatetime = $row->updatetime;
			$atype = $row->atype;
			$cid = $row->cid;
			$atitle = $row->title;
		}
		
		$data['acontent'] = $acontent;
		$data['author'] = $author;
		$data['updatetime'] = date('Y年m月d日', strtotime($updatetime));;
		$data['atitle'] = $atitle;
		
		//find template
		$tarray = $this->cms_model->findtemplate($aid, 1);
		$tid = $tarray['tid'];
		$tcontent = $tarray['content'];
		$sid = $tarray['sid'];
		if(empty($tcontent))
			return ;
			
		$data['cid'] = $cid;
			
		//menu columns
		$data['menucols'] = $this->cms_model->listmenucols($sid, 'menu', 1);
						
		//nav column
		$navcolarray = $this->cms_model->getnavcols($cid, 1);
		$data['navcolarray'] = $navcolarray;
	
		//column name
		$data['colname'] = $this->cms_model->getcolname($cid);
		
		/*----------------------*/
		
		//view by smarty
		$tplfilename = $tid.'_html.tpl';
		$output = $this->smarty->view($tplfilename,$data,True);
		//$output = iconv('GB2312','UTF-8',  $output);
		$filepath = $folderPath.'/'.$aid.'.html';
		$fp = fopen($filepath, "w");
		fwrite($fp, $output);
		fclose($fp);
		
		$this->gen_pnum++;
	}
	
	public function sync(){
		//check auth
		$userid = $_SESSION['qf_userid'];
		if($userid != 'admin'){
			$this->load->view('blank_view');
			return ;
		}
		$this->load->view('sync_view');
		
	}
	
	public function dosync(){
		//sync column
		//$this->cms_model->dosynccol(0,'');
		
		//sync article
		//$this->cms_model->dosyncart();
		
		//sync article att
		//$this->cms_model->dosyncartatt();
		
		echo('ok');
	}
}
